<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/15
 * Time: 14:49
 */

namespace Admin\Controller;


class MoneyController extends BaseController
{
    /*
     * @auth: 竹晓玉
     * @function:   获取图表信息
     * @time:   2016年12月2日14:36:44
     * */
    public function getchartslist(){
//        $startTime = empty(I('get.startime'))?(time()):I('get.startime');
//        $endTime = empty(I('get.endtime'))?time():I('get.endtime');


        if(empty(I('get.startime'))){
            $start = date('Y-m-d', mktime(0,0,0,date('m')-1,1,date('Y'))); //上个月的开始日期
            $startTime=strtotime($start);
        }else
            $startTime = strtotime(I('get.startime'));

        if(empty(I('get.endtime'))){
            $m = date('Y-m-d', mktime(0,0,0,date('m')-1,1,date('Y'))); //上个月的开始日期
            $t = date('t',strtotime($m)); //上个月共多少天
            $end = date('Y-m-d', mktime(0,0,0,date('m')-1,$t,date('Y'))); //上个月的结束日期
            $endTime=strtotime($end);
        }else
            $endTime = strtotime(I('get.endtime'))+86400;


        $map['time']=array('BETWEEN',array($startTime,$endTime));
        $reportIncomeP = D('ReportIncome');
        $resultIncomeProfit = $reportIncomeP->getchartslist_income_profit($map);
        foreach ($resultIncomeProfit as &$v){
            $v['time'] = date('Y-m-d',$v['time']);
        }

        $reportSellCourseP = D('ReportSellCourse');
        $resultSellCourse = $reportSellCourseP->getchartslist_sell_course($map);
        foreach ($resultSellCourse as &$v){
            $v['time'] = date('Y-m-d',$v['time']);
        }
        if(!$resultSellCourse && !$resultIncomeProfit)
            $this->outOInfo(array(
                'income_profit'=>array(),
                'sell_course'=>array(),
            ),1);
        if(!$resultSellCourse && $resultIncomeProfit)
            $this->outOInfo(array(
                'income_profit'=>$resultIncomeProfit,
                'sell_course'=>array(),
            ),1);
        if($resultSellCourse && !$resultIncomeProfit)
            $this->outOInfo(array(
                'income_profit'=>array(),
                'sell_course'=>$resultSellCourse,
            ),1);
        $this->outOInfo(array(
            'income_profit'=>$resultIncomeProfit,
            'sell_course'=>$resultSellCourse,
        ));
    }

    /* 获取销售记录列表 */
    public function get_list(){

        $dean = I('get.dean');       //合伙人（园长）
        $nickname = I('get.nickname');   //用户
        $expand = I('get.expand');     //教练
        $teacher = I('get.teacher');     //老师
        $course = I('get.course');     //课程

        $page = empty(I('get.p'))?1:I('get.p');
        $memberRelativeMap = array();

        $memberP = D('Member');
        if(!empty($course))
            $map['t_money.goods_id'] = array('EQ',$course);
        if(!empty($dean))
            if($userInfo = $memberP->getUserInfo($dean)){
                $memberRelativeMap['dean_id'] = $userInfo['id'];
            }else{
                $this->outOInfo('获取合伙人失败',0);
            }

        if(!empty($nickname))
            if($userInfo = $memberP->getUserInfo($nickname)){
                $memberRelativeMap['user_id'] = array('EQ',$userInfo['id']);
            }else{
                $this->outOInfo('获取用户失败',0);
            }

        if(!empty($teacher))
            if($userInfo = $memberP->getUserInfo($teacher)){
                $memberRelativeMap['teacher_id'] = $userInfo['id'];
            }else{
                $this->outOInfo('获取老师失败',0);
            }

        if(!empty($expand))
            if($userInfo = $memberP->getUserInfo($expand)){
                $memberRelativeMap['expand_id'] = $userInfo['id'];
            }else{
                $this->outOInfo('获取教练失败',0);
            }

        if(sizeof($memberRelativeMap) != 0 ){
            $memberRelativeP = D('MemberRelative');
            if($ids = $memberRelativeP->searchOne($memberRelativeMap)){

                $user_ids = array();
                foreach ($ids as $v){
                    array_push($user_ids,$v['user_id']);
                }
                $map['t_money.user_id'] = array('IN',$user_ids);
            }else{
                $this->outOInfo('查找关系错误，未能查找到相应信息',0);
            }
        }



        $endDate = empty(I('get.endDate'))?time():strtotime(I('get.endDate'))+86400;
        $startDate = I('get.startDate');
        switch (I('get.searchTime')){
            case 1:
                $startDate = empty($startDate)?strtotime(date("Y-m-d")):strtotime($startDate);
                $map['t_money.achive_time'] = array('BETWEEN',array($startDate,$endDate));
                break;
            case 2:
                $startDate = empty($startDate)?strtotime('-1 week',date("Y-m-d")):strtotime($startDate);
                $map['t_money.achive_time'] = array('BETWEEN',array($startDate,$endDate));
                break;
            case 3:
                $startDate = empty($startDate)?strtotime('-1 months',date("Y-m-d")):strtotime($startDate);
                $map['t_money.achive_time'] = array('BETWEEN',array($startDate,$endDate));
                break;
            case 4:
                break;
            default:
                $startDate = empty($startDate)?strtotime(date("Y-m-d")):strtotime($startDate);
                $map['t_money.achive_time'] = array('BETWEEN',array($startDate,$endDate));
                break;
        }

        $moneyP = D('Money');
        $map['t_money.goods_type'] = array('EQ',1);
        $map['t_money.amount'] = array('GT',0);
        $map['t_money.status'] = array('EQ',1);
//        $this->outOInfo($map,0);
        $result = $moneyP->get_list($map,$page);
        foreach ($result as &$v){
            $v['achive_time_txt'] = empty($v['achive_time'])?$v['achive_time']:date("Y-m-d H:i", $v['achive_time']);
	    $v['profit'] 	= round($v['money_amount'] - $v['deduct'], 2);
        }
//dump($result);
//        $this->outOInfo($result,0);
        if($result !== false)
            $this->outOInfo(array(
                'list' => $result,
                'pages'=>$page,
            ));
        $this->outOInfo('获取列表失败',0);
    }
    /**
     * 导出提现信息Excel
     *
     */
    function outList(){
        $dean = I('get.dean');       //合伙人（园长）
        $nickname = I('get.nickname');   //用户
        $expand = I('get.expand');     //教练
        $teacher = I('get.teacher');     //老师
        $course = I('get.course');     //课程


        $memberRelativeMap = array();

        $memberP = D('Member');
        if(!empty($dean))
            if($userInfo = $memberP->getUserInfo($dean)){
                $memberRelativeMap['dean_id'] = $userInfo['id'];
            }else{
                $this->outOInfo('获取合伙人失败',0);
            }

        if(!empty($nickname))
            if($userInfo = $memberP->getUserInfo($nickname)){
                $memberRelativeMap['user_id'] = array('EQ',$userInfo['id']);
            }else{
                $this->outOInfo('获取用户失败',0);
            }

        if(!empty($teacher))
            if($userInfo = $memberP->getUserInfo($teacher)){
                $memberRelativeMap['teacher_id'] = $userInfo['id'];
            }else{
                $this->outOInfo('获取老师失败',0);
            }

        if(!empty($expand))
            if($userInfo = $memberP->getUserInfo($expand)){
                $memberRelativeMap['expand_id'] = $userInfo['id'];
            }else{
                $this->outOInfo('获取教练失败',0);
            }

        if(sizeof($memberRelativeMap) != 0 ){
            $memberRelativeP = D('MemberRelative');
            if($ids = $memberRelativeP->searchOne($memberRelativeMap)){

                $user_ids = array();
                foreach ($ids as $v){
                    array_push($user_ids,$v['user_id']);
                }
                $map['t_money.user_id'] = array('IN',$user_ids);
            }else{
                $this->outOInfo('查找关系错误，未能查找到相应信息',0);
            }
        }



        $endDate = empty(I('get.endDate'))?time():strtotime(I('get.endDate'));
        $startDate = I('get.startDate');
        switch (I('get.searchTime')){
            case 1:
                $startDate = empty($startDate)?strtotime(date("Y-m-d")):strtotime($startDate);
                $map['t_money.achive_time'] = array('BETWEEN',array($startDate,$endDate));
                break;
            case 2:
                $startDate = empty($startDate)?strtotime('-1 week',date("Y-m-d")):strtotime($startDate);
                $map['t_money.achive_time'] = array('BETWEEN',array($startDate,$endDate));
                break;
            case 3:
                $startDate = empty($startDate)?strtotime('-1 months',date("Y-m-d")):strtotime($startDate);
                $map['t_money.achive_time'] = array('BETWEEN',array($startDate,$endDate));
                break;
            case 4:
                break;
            default:
                $map['t_money.achive_time'] = array('BETWEEN',array($startDate,$endDate));
                break;
        }

        $moneyP = D('Money');
        $map['t_money.goods_type'] = array('EQ',1);
        $map['t_money.amount'] = array('GT',0);
        $map['t_money.status'] = array('EQ',1);
//        $this->outOInfo($map,0);
        $result = $moneyP->getOutlist($map);
        //dump($result);exit;
        foreach ($result as &$v){
            $v['achive_time_txt'] = empty($v['achive_time'])?$v['achive_time']:date("Y-m-d H:i", $v['achive_time']);
            $v['profit'] = $v['money_amount']-$v['deduct'];
        }



        $title  = array(
            '记录ID',
            '会员Id',
            '购买人',
            '购买课程',
            '售价',
            '购买价',
            '利润',
            '订单号',
            '时间',
        );
        $key    = array(
            'id',
            'user_id',
            'nickname',
            'name',
            'price',
            'money_amount',
            'profit',
            'trade_no',
            'achive_time_txt',

        );

        foreach($result as $val){
            foreach($key as $k){
                $info[$k]   = $val[$k];
            }
            $data[]     = $info;
        }

        out_excel($title, $data, '欣乐土销售记录统计');
    }


    /**
     * 获取资金分配记录
     * @author  王中艺 <wangzy_smile@qq.com>
     * @param   $p 页码数
     * @param   $keyword 关键词
     * @param   $date_start 开始时间
     * @param   $date_end 结束时间
     * @return  $list json [<description>]
     */
    function getDeductList(){
        $page   = $this->iInfo['p'] ? $this->iInfo['p'] : 1;
        $keyword    = $this->iInfo['keyword'] ? $this->iInfo['keyword'] : false;
        $timeS  = $this->iInfo['date_start'] ? 
            strtotime($this->iInfo['date_start']) : false;
        $timeE  = $this->iInfo['date_end'] ? 
            strtotime($this->iInfo['date_end'].' +1 day') : false;
        $getType    = $this->request('get_type', 'all');

        $pageHtml   = true;
        $total  = true;
        if($getType == 'all'){
            $list   = D('Deduct')->getList($keyword, $timeS, $timeE, $page, $pageHtml, $total);
        }else{
            $list   = D('Deduct')->getExpandList($keyword, $timeS, $timeE, $page, $pageHtml, $total);
        }
        
        if($list === false)
            $this->outOInfo(D('Money')->errMsg, 0);
        $this->outOInfo(array('list' => $list, 'page_html' => $pageHtml, 'total' => $total));
    }

    /**
     * 导出Excel
     * @param   $start 开始位置
     * @param   $lenght 长度
     * @param   $keyword 关键词
     * @param   $date_start 开始时间
     * @param   $date_end 结束时间
     * @return  excel file [<description>]
     */
    function outExcelDeductList(){
        $start  = isset($this->iInfo['start']) ? $this->iInfo['start'] : false;
        $length     = $this->iInfo['length'] ? $this->iInfo['length'] : 1000;
        $keyword    = $this->iInfo['keyword'] ? $this->iInfo['keyword'] : false;
        $timeS  = $this->iInfo['date_start'] ? 
            strtotime($this->iInfo['date_start']) : false;
        $timeE  = $this->iInfo['date_end'] ? 
            strtotime($this->iInfo['date_end'].' +1 day') : false;

        $data   = D('Deduct')->outExcel($start, $length, $keyword, $timeS, $timeE);
        if(is_numeric($data))
            $this->outOInfo(array('count' => $data));

        $title  = array(
            '订单ID', '用户ID', '用户昵称', '真实姓名', '用户角色', '交易类型', '交易时间', '交易金额',
            '交易单号', '平台利润','获得金额', '分配比例'
        );
        foreach($data as &$item){
            $d['money_id']    = $item['money_id'];
            $d['user_id']   = $item['user_id'];
            $d['nickname']  = $item['nickname'];
            $d['truename']  = $item['truename'];
            $d['role_text'] = $item['role_text'];
            $d['goods_type']    = $item['goods_type_text'];
            $d['create_date']   = date('Y-m-d H:i:s', $item['create_time']);
            $d['amount']    = $item['amount'];
            $d['trade_no']  = $item['trade_no'];
            $d['profit']    = $item['profit'];
            $d['get_amount']    = $item['get_amount'];
            $d['percent']   = $item['percent'];
            $item   = $d;
        }
        out_excel($title, $data, 'deduct_list_'.$start);
    }

    /**
     * 获取详细交易信息
     * @param   $id
     * @return  $moneyInfo and $deductInfo
     */
    function getDetailItem(){
        $client     = $this->unEmptyParam(['id']);
        $this->response([
            'money_info'    => D('Money')->detailInfo($client['id']),
            'deduct_info'   => D('Deduct')->detailInfo($client['id'])
        ]);
    }

    /**
     * 获取下级用户分红记录
     * @param   $user_id
     * @param   $p
     * @return  $list
     */
    function getChildDeductList(){
        $this->unEmptyParam(['user_id']);

        $userId     = $this->request('user_id');
        $page   = $this->request('p', 1);
        $pageHtml   = true;
        
        $list   = D('Deduct')->getChildList($userId, $page, $pageHtml);
        if($list === false)
            $this->outOInfo(D('Deduct')->errMsg, 0);
        $this->outOInfo(['list' => $list, 'page_html' => $pageHtml]);
    }

}
